// pages/shopping/orderConfirm/orderConfirm.js
var app = getApp();
var mta = require('../../../utils/mta_analysis.js');
var WxParse = require('../../../wxParse/wxParse.js');
var address_id= ''; //地址id
var univalent= ''; //订单类型为购买时，产品单价
var total_money_all='';
var isOrder= false; //提交
Page({

  /**
   * 页面的初始数据
   */
  data: {
    equipments_id: 73, //设备id
    choose_package_id: 86, //所选套餐id
    user_id: 31, //用户id
    address_icon: '../../../images/address_icon.png',
    position_r: '../../../images/position_r.png',
    go_right: '../../../images/go_right.png',
    close_invoice: '../../../images/close_invoice.png',
    important_icon: '../../../images/important_icon.png',
    add_red: '../../../images/add_red.png',
    address: {}, //地址信息
    packageInfo: {}, //套餐信息
    address_len: 0, //地址个数
    buyNum: 1, //购买数量
    type_list: ['纸质发票', '电子普通发票'], //发票类型
    header_list: ['个人', '单位'], //发票抬头
    typeActiveIndex: 0, //发票类型选择
    headerActiveIndex: 0, //发票抬头选择
    isShowMask: true,
    goodsInfo: {}, //产品信息
    real_money: 0.00, //实际付款
    total_amount: 0.00, //实际付款
    all_money: 0.00, //订单总价
    deposit_all: 0.00, //总押金
    order_type: 1, //订单类型1租赁订单2购买订单3积分订单，默认1
    invoice_type: 1, //发票类型1纸质发票2电子发票，如果开发票，必须传
    invoice_id: "", //发票ID，如果开发票，必须传
    is_invoice: 1, //是否开发票 默认1不开发票
    invoiceList: '', //发票列表
    name_pers: '', //个人姓名
    num_persnum: '', //个人电话号码
    dw_names: '', //单位名称
    num_nasui: '', //纳税编号
    remarks: '', //买家留言
    isShowNote: false,
    order_type: '', //订单类型 1：租赁，2：购买
    hasCoupon: false, // 是否可用优惠券
    coupon_id: '', // 优惠券ID
    coupon_money: 0, // 优惠券金额
    coupon_name: '使用', // 优惠券名称
    ishowmodel: true,
    checked: true,
    orderNotice: '', // 下单须知
    invoiceNotice: '', // 发票须知
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //console.log(options)
    let that = this;
    mta.Page.init();
    var order_type = options.order_type;
    that.setData({
      order_type: order_type,
      equipments_id: options.equipments_id
    })
    if (order_type == 1) {
      // 租赁
      that.setData({
        choose_package_id: options.choose_package_id,
      })
      that.getInvoiceList(); //获取发票信息
    } else if (order_type == 2) {
      // 购买
      that.setData({
        choose_package_id: '',
      })

    }
    that.getAddressInfo(); // 获取地址信息
    that.getGoodsInfo();   // 获取商品信息

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
     address_id = wx.getStorageSync('address_id');
    console.log('地址id', address_id);
    //有选择的id 已有选择id为主
    if (address_id != '') {
      console.log('id',address_id);
      that.addressDisplay(address_id); //重新获取地址信息
    } else {
      that.setData({
        address: {},
        address_len: 0
      })
      address_id='';
      that.getAddressInfo();
    }
    console.log('hasCoupon', that.data.hasCoupon);
    // 获取优惠券信息
    if (that.data.hasCoupon) {
      let coupon_money = wx.getStorageSync('coupon_money')
      if(that.data.goodsInfo.equipments_line == 3){
        if(coupon_money >= 48){
          coupon_money = that.data.goodsInfo.equipments_purchase_money
        }else{
          let unit = 48 - coupon_money
          coupon_money = that.data.goodsInfo.equipments_purchase_money - unit
        }
      }
      
      that.setData({
        coupon_id: wx.getStorageSync('coupon_id'), // 优惠券ID
        coupon_money, // 优惠券金额
        coupon_name: wx.getStorageSync('coupon_name'), // 优惠券名称
      })
    }
  },

  // 查询是否有优惠券可以用
  getHasCoupon() {
    var that = this;
    var total_money = 0;
    // 1表示租赁商品，2是购买商品
    if (that.data.order_type == 1) {
      total_money = that.data.packageInfo.total_money * that.data.buyNum; // 付款金额
    } else if (that.data.order_type == 2) {
      total_money = that.data.goodsInfo.equipments_purchase_money * that.data.buyNum; // 付款金额
    }
    // ajax请求
    app.ajax({
      url: 'User/Coupon/hasCoupon',
      data: {
        "total_money": total_money
      },
      success: function(res) {
        if (res.data.code == 1000) {
          that.setData({
            hasCoupon: true
          })
        }
        console.log('是否可以用优惠券', res)
      }
    })
  },

  // 优惠券点击事件
  chooseCoupon: function() {
    var that = this;
    var total_money = 0;
    // 1表示租赁商品，2是购买商品
    if (that.data.order_type == 1) {
      total_money = that.data.packageInfo.total_money * that.data.buyNum; // 付款金额
    } else if (that.data.order_type == 2) {
      total_money = that.data.goodsInfo.equipments_purchase_money * that.data.buyNum; // 付款金额
      // if(that.data.goodsInfo.equipments_line == 3 )
    }
    console.log('是否选择优惠券',total_money)
    if (that.data.hasCoupon) {
      wx.navigateTo({
        url: '../../user/coupon/coupon?money=' + total_money,
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    //wx.removeStorageSync('address_id')//同步清除地址id缓存
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.removeStorageSync('address_id') //同步清除地址id缓存
  },

  //遮罩时阻止滚动
  myCatchTouch: function() {
    return;
  },

  // 买家留言
  inputRemark: function(e) {
    var that = this;
    var remarks = e.detail.value;
    that.setData({
      remarks: remarks
    })
  },

  // 发票须知
  openNode() {
    var that = this;
    // ajax请求
    app.ajax({
      url: 'Common/Article/getArticle',
      data: { cate_sn: 'ATl58qSj' },
      success: function (res) {
        if (res.data.code == 1000) {
          var invoiceNotice = res.data.data[0].content;
          that.setData({
            invoiceNotice: invoiceNotice
          })
          WxParse.wxParse('invoice_notice', 'html', invoiceNotice, that, 5);
        }
        console.log('发票须知', res);
      }
    })
    that.setData({
      isShowNote: true
    })
  },

  //关闭发票须知
  closeNote() {
    var that = this;
    that.setData({
      isShowNote: false
    })
  },
  //关闭发票须知
  confirmfun() {
    var that = this;
    that.setData({
      isShowNote: false
    })
  },

  //数量加减
  changeNUm: function(e) {
    var that = this;
    let type = e.currentTarget.dataset.type;
    let buyNum = that.data.buyNum;
    var deposit = that.data.goodsInfo.deposit;
    var order_type = that.data.order_type;
    var total_money = that.data.packageInfo.total_money;
    console.log('s',order_type);
    if (order_type == 2) {
      total_money = univalent;
    }
    console.log('m',total_money)
    
    // var univalent = univalent;

    if (type == 0) { //减
      buyNum--;
    } else { //加
      buyNum++;
    }
    if (buyNum < 1) {
      buyNum = 1;
    }
    var deposit_all = parseFloat(deposit * buyNum).toFixed(2);
    if (order_type == 2) {
      var deposit_all = 0;
    }
    // if (order_type == 1) {

         total_money_all = parseFloat(total_money * buyNum).toFixed(2);
      var all_money = parseFloat(parseFloat(deposit_all) + parseFloat(total_money_all)).toFixed(2);
      var real_money = parseFloat(all_money).toFixed(2);
      that.setData({
        buyNum: buyNum,
        deposit_all: deposit_all,
        all_money: all_money,
        real_money: real_money
      })
    // } else if (order_type == 2) {
    //   var real_money = parseFloat(univalent * buyNum).toFixed(2);
    //   that.setData({
    //     buyNum: buyNum,
    //     real_money: real_money
    //   })
    // }
    that.getHasCoupon(); // 判断是否可用优惠券

  },
  //遮罩时阻止滚动
  myCatchTouch: function() {
    return false;
  },
  //类型选择
  changeType: function(e) {
    var i = e.currentTarget.dataset.index;
    this.setData({
      //typeActiveIndex:i,
      typeActiveIndex: 0
    })
  },
  //抬头选择
  changeHeader: function(e) {
    var that = this;
    var i = e.currentTarget.dataset.index;
    this.setData({
      headerActiveIndex: i
    })
  },
  //关闭发票弹窗
  closeInvoice: function() {
    this.setData({
      isShowMask: true
    })
  },
  //选择发票
  chooseInvoice: function() {
    this.setData({
      isShowMask: false
    })
  },
  //手机号码
  cheng_persname(e) {
    var that = this;
    that.setData({
      name_pers: e.detail.value
    })
  },
  //手机号码
  cheng_persnum(e) {
    var that = this;
    that.setData({
      num_persnum: e.detail.value
    })
  },
  //输入单位名称
  chengname(e) {
    var that = this;
    that.setData({
      dw_names: e.detail.value
    })
  },
  //纳税编号
  chengnasui(e) {
    var that = this;
    that.setData({
      num_nasui: e.detail.value
    })
  },
  //确认发票选择
  okInvoice: function() {
    var that = this;
    var hIndex = that.data.headerActiveIndex; //0是个人 1是单位
    //var inv_id = that.data.invoiceList[hIndex].invoice_id;
    var pers_name = that.data.name_pers; //个人姓名
    var pers_tel = that.data.num_persnum; //个人电话
    var numreg = /^[1][3-9][\d]{9}$/; //手机号码正则  
    if (pers_name == '' && hIndex == 0) {
      app.showToast('姓名不能为空', "none", 2000, function() {});
      return false;
    }
    if (pers_tel == '' && hIndex == 0) {
      app.showToast('手机号码不能为空', "none", 2000, function() {});
      return false;
    }
    if (numreg.test(pers_tel) == false && hIndex == 0) {
      app.showToast('请输入正确的手机号码', "none", 2000, function() {});
      return false;
    }

    var jt_names = that.data.dw_names; //单位名
    var nasui_num = that.data.num_nasui; //纳税号不能为空
    if (jt_names == '' && hIndex == 1) {
      app.showToast('单位名不能为空', "none", 2000, function() {});
      return false;
    }
    if (nasui_num == '' && hIndex == 1) {
      app.showToast('纳税人识别号不能为空', "none", 2000, function() {});
      return false;
    }
    that.setData({
      isShowMask: true,
      is_invoice: 2
    })
    if (hIndex == 0) { //个人
      app.ajax({
        url: 'User/Invoice/addEditInvoice',
        data: {
          type: 1,
          name: pers_name,
          tel: pers_tel
        },
        success: function(res) {
          if (res.data.code == 1000) {
            that.setData({
              invoice_id: res.data.data.invoice_id
            })
          } else {
            app.showToast(res.data.message, "none", 2000, function() {});
          }
        }
      })
    } else { //企业
      app.ajax({
        url: 'User/Invoice/addEditInvoice',
        data: {
          type: 2,
          name: jt_names,
          tax_no: nasui_num,
        },
        success: function(res) {
          if (res.data.code == 1000) {
            that.setData({
              invoice_id: res.data.data.invoice_id
            })
          } else {
            app.showToast(res.data.message, "none", 2000, function() {});
          }
        }
      })
    }

  },
  // 获取发票列表
  getInvoiceList() {
    var that = this;
    // ajax请求
    app.ajax({
      url: 'User/Invoice/invoiceList',
      data: {},
      success: function(res) {
        if (res.data.code == 1000) {
          for (var j = 0; j < res.data.data.length; j++) {
            if (res.data.data[j].type == 1) {
              that.setData({
                invoiceList: res.data.data,
                name_pers: res.data.data[j].name,
                num_persnum: res.data.data[j].tel
              })
            } else if (res.data.data[j].type == 2) {
              that.setData({
                invoiceList: res.data.data,
                dw_names: res.data.data[j].name,
                num_nasui: res.data.data[j].tax_no
              })
            }
          }
        }
      }
    })
  },
  //提交订单
  goPayment: function(e) {
    var that = this;
    app.ajax({
      url: "User/Order/getOrderOne",
      method: "POST",
      data: {},
      success: function(res) {
        console.log(res)
        // 没有新装未支付的订单
        if(res.data.code == -1000) {
      //    app.saveFormId(e.detail.formId);
          // if (isOrder) {
          //   return false;
          // }
          var order_type = that.data.order_type;
          var equipments_id = that.data.equipments_id;
          if (order_type == 1) {
            var equipments_rental_package_id = that.data.choose_package_id;
          } else if (order_type == 2) {
            var equipments_rental_package_id = '';
          }
          var equipment_num = that.data.buyNum;
          var is_invoice = that.data.is_invoice;
          var invoice_type = that.data.invoice_type;
          var invoice_id = that.data.invoice_id;
          var pers_stel = that.data.num_persnum; //个人电话
          var remarks = that.data.remarks;
          var coupon_id = that.data.coupon_id; // 优惠券ID
          if (address_id == '') {
            app.showToast('您还没选择地址，请先选择地址', "none", 2000, function() {});
            return false;
          }
          if (equipment_num == '' && equipment_num > 0) {
            app.showToast('设备数量不能为空', "none", 2000, function() {});
            return false;
          }
          if (that.data.checked == false) {
            app.showToast('请勾选下单须知');
            return false;
          }
          app.ajax({
            url: 'User/Order/addOrder',
            method: "POST",
            data: {
              order_type: order_type,
              equipments_id: equipments_id,
              equipments_rental_package_id: equipments_rental_package_id,
              address_id: address_id,
              equipment_num: equipment_num,
              is_invoice: is_invoice,
              invoice_type: invoice_type,
              invoice_id: invoice_id,
              invoice_recevice_tel: pers_stel,
              remarks: remarks,
              coupon_id: coupon_id
            },
            success: function(res) {
              if (res.data.code == 1000) {
                isOrder=true
                wx.removeStorageSync('address_id') //跳转页面---同步----清除地址id缓存
                app.showToast(res.data.message);
                wx.redirectTo({
                  url: '../payment/payment?order_id=' + res.data.data.order_id + '&type=1',
                })
              } else {
                app.showToast(res.data.message);
              }
            }
          })
        } else {
          wx.showModal({
            title: '存在未支付订单，请前往支付',
            content: '',
            complete: (res) => {
              if (res.cancel) {
              }
              if (res.confirm) {
                console.log('confirm')
                wx.redirectTo({
                  url: '../../user/myOrderList/myOrderList?tables=1',
                })
              }
            }
          })
        }        
      },
      fail: function(res) {
        console.log('请求错误')
      }
    })
  },

  //获取用户信息
  // getUserInfo:function(){
  //   var that = this;
  //   var user_id = that.data.user_id;
  //   app.ajax({
  //     url: 'User/User/getUserInfo',
  //     method: "POST",
  //     data: { user_id: user_id },
  //     success: function (res) {
  //       console.log(res)
  //       if (res.data.code == 1000) {

  //       } else {
  //         app.showToast("网络错误,请稍后重试", "none", 2000, function () { });
  //       }
  //     }
  //   })
  // },

  //查询地址信息
  getAddressInfo: function() {
    var that = this;
    var user_id = that.data.user_id;
    app.ajax({
      url: 'User/Useraddress/addressList',
      method: "POST",
      data: {
        page: 1,
        pageSize: 100
      },
      success: function(res) {
        //console.log(res)
        if (res.data.code == 1000) {
          var address = res.data.data[0];
          var address_len = res.data.data.length;
           address_id = res.data.data[0].address_id;
          that.setData({
            address: address,
            address_len: address_len
          })
        } else {
          // app.showToast(res.data.message);
        }
      }
    })
  },
  //单个地址信息
  addressDisplay: function(address_id) {
    var that = this;
    app.ajax({
      url: 'User/Useraddress/addressDisplay',
      method: "POST",
      data: {
        address_id: address_id
      },
      success: function(res) {
        //console.log(res)
        if (res.data.code == 1000) {
          var addressb = res.data.data;
          var addressb_len = 1;
           address_id = res.data.data.address_id;
          that.setData({
            address: addressb,
            address_len: addressb_len
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //查询产品信息
  getGoodsInfo: function() {
    var that = this;
    var equipments_id = that.data.equipments_id;
    app.ajax({
      url: 'User/Equipment/equipmentsDetail',
      method: "POST",
      data: {
        equipments_id: equipments_id
      },
      success: function(res) {
        //console.log(res)
        if (res.data.code == 1000) {
          var goodsInfo = res.data.data;
          var order_type = that.data.order_type;
              univalent = res.data.data.equipments_purchase_money;
          var deposit = res.data.data.deposit;
          var deposit_all = parseFloat(deposit * 1).toFixed(2);

          that.setData({
            goodsInfo: goodsInfo,
            buyNum: 1,
            deposit_all: deposit_all,
            real_money: univalent
          })
          if (order_type == 1) {
            that.getPackageInfo(deposit_all); //查询套餐信息
          } else {
            that.setData({
              all_money: res.data.data.equipments_purchase_money
            })
            that.getHasCoupon(); // 判断是否可用优惠券
          }
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //查询套餐信息
  getPackageInfo: function(deposit_all) {
    var that = this;
    var choose_package_id = that.data.choose_package_id;
    var deposit_all = deposit_all;
    app.ajax({
      url: 'User/Equipment/packageDetail',
      method: "POST",
      data: {
        package_id: choose_package_id
      },
      success: function(res) {
        if (res.data.code == 1000) {
          var packageInfo = res.data.data;

          var total_money = parseFloat(res.data.data.total_money).toFixed(2);
               total_money_all = parseFloat(total_money * 1).toFixed(2);
          var all_money = parseFloat(parseFloat(deposit_all) + parseFloat(total_money_all)).toFixed(2);
          var real_money = parseFloat(all_money).toFixed(2);

          that.setData({
            packageInfo: packageInfo,
            all_money: all_money,
            real_money: real_money
          })
          
          that.getHasCoupon(); // 判断是否可用优惠券
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //跳转我的地址列列表
  myAddressList() {
    var that = this;
    var address_len = that.data.address_len;
    if (address_len == 0) {
      let address_id_s = '';
      var Type = 1;
      wx.navigateTo({
        url: '../../user/editAddress/editAddress?address_id=' + address_id_s + '&type=' + Type,
      })
    } else {
      wx.navigateTo({
        url: '../../user/myAddressList/myAddressList?on_way=' + 2,
      })
    }

  },

  //选择
  checkChange: function () {
    let that = this;
    let checked = !that.data.checked;
    that.setData({
      checked: checked
    })
  },

  // 下单须知
  openNotice() {
    let that = this;
    // ajax请求
    app.ajax({
      url: 'Common/Article/getArticle',
      data: { cate_sn: 'A4C9kaSr' },
      success: function (res) {
        if (res.data.code == 1000) {
          var orderNotice = res.data.data[0].content;
          that.setData({
            orderNotice: orderNotice
          })
          WxParse.wxParse('order_notice', 'html', orderNotice, that, 5);
        }
        console.log('下单须知',res);
      }
    })
    that.setData({
      ishowmodel: false
    })
  },
  //关闭下单须知
  closeNote: function() {
    let that = this;
    that.setData({
      ishowmodel: true
    })
  },
  //不同意下单须知
  cancel: function() {
    let that = this;
    that.setData({
      ishowmodel: true,
      checked:false
    })
  },
  //同意下单须知
  confirm: function() {
    let that = this;
    that.setData({
      ishowmodel: true,
      checked: true
    })
  },

})